import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:xcite/core/services/open_launcher.dart';
import 'package:xcite/core/utils/ali.dart';

import '../../core/models/topic_model.dart';
import '../../core/providers/topic_provider.dart';
import '../../core/providers/user_provider.dart';
import '../../core/utils/popup_helper.dart';
import '../../core/utils/toast_helper.dart';
import '../../core/widgets/report_popup.dart';

class TopicDetailScreen extends ConsumerStatefulWidget {
  final String topicId;

  const TopicDetailScreen({super.key, required this.topicId});

  @override
  ConsumerState<TopicDetailScreen> createState() => _TopicDetailScreenState();
}

class _TopicDetailScreenState extends ConsumerState<TopicDetailScreen> {
  final TextEditingController _contentController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  List<AssetEntity> _selectedAssets = [];

  @override
  void dispose() {
    _contentController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/common_bg_2.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child:
              [
                _buildTopNavigationBar(),
                SizedBox(height: 20.h),
                _buildTopicDisplay(),
                SizedBox(height: 16.h),
                _buildShareListContainer().expanded(),
                SizedBox(height: 6.h),
                GestureDetector(
                  onTap: () {
                    Open.openLaunch(
                      'https://www.freeprivacypolicy.com/live/2908db45-eaa5-4be2-bf12-428f9bbadb26',
                    );
                  },
                  child: Text(
                    'EULA',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Colors.white.withValues(alpha: 0.70),
                      fontSize: 14.sp,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w400,
                      decoration: TextDecoration.underline,
                      decorationColor: Colors.white,
                    ),
                  ),
                ),
                _buildBottomInputArea(),
              ].toColumn(),
        ),
      ),
    );
  }

  Widget _buildTopNavigationBar() {
    return [
      Container(
        width: 30.w,
        height: 30.w,
        decoration: BoxDecoration(color: Colors.black, shape: BoxShape.circle),
        child:
            Icon(
              Icons.arrow_back_ios_new,
            ).iconSize(16.sp).iconColor(Colors.white).center(),
      ).inkWell(onTap: () => GoRouter.of(context).pop()),
      Expanded(
        child: Text(
          'Spring Outing Topics',
          textAlign: TextAlign.center,
          style: TextStyle(
            fontSize: 24.sp,
            fontWeight: FontWeight.bold,
            color: Colors.black,
            fontFamily: 'PoetsenOne',
          ),
        ),
      ),
      SizedBox(width: 16.w),
    ].toRow().padding(horizontal: 16.w);
  }

  Widget _buildTopicDisplay() {
    final topics = ref.watch(outingTopicProvider);
    OutingTopicEntity? topic;
    try {
      topic = topics.firstWhere((t) => t.topicId == widget.topicId);
    } catch (e) {
      topic = topics.isNotEmpty ? topics.first : null;
    }

    if (topic == null) {
      return Container(
        height: 94.h,
        margin: EdgeInsets.symmetric(horizontal: 16.w),
        child:
            Text(
              'Topic not found',
            ).fontSize(16.sp).textColor(Colors.grey).center(),
      );
    }

    return Container(
      height: 94.h,
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/resources/topic_card_bg_1.png'),
          fit: BoxFit.fill,
        ),
      ),
      child: [
        Container(
          width: 54.w,
          height: 54.w,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: Color(0xFF2AB061),
          ),
          child:
              Image.asset(
                'assets/resources/topic_icon.png',
                width: 28.w,
                height: 28.w,
              ).center(),
        ),
        SizedBox(width: 16.w),
        Expanded(
          child: Text(
            topic.description,
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w600,
              color: Colors.black87,
            ),
            maxLines: 3,
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ].toRow(crossAxisAlignment: CrossAxisAlignment.center),
    );
  }

  Widget _buildShareListContainer() {
    ref.watch(outingTopicProvider);
    final topicNotifier = ref.read(outingTopicProvider.notifier);
    final topicShares = topicNotifier.getTopicShares(widget.topicId);

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: Container(
        padding: EdgeInsets.only(top: 16.h, bottom: 16.h),
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/topic_detail_bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: _buildShareList(topicShares),
      ),
    );
  }

  Widget _buildShareList(List<TopicShareEntity> shares) {
    if (shares.isEmpty) {
      return Text(
        'No shares yet',
      ).fontSize(16.sp).textColor(Colors.grey).center();
    }

    return ListView.builder(
      controller: _scrollController,
      padding: EdgeInsets.all(16.w),
      itemCount: shares.length,
      itemBuilder: (context, index) {
        final share = shares[index];
        return _buildShareItem(share);
      },
    );
  }

  Widget _buildShareItem(TopicShareEntity share) {
    final userNotifier = ref.read(userProvider.notifier);
    final allUsers = userNotifier.getAllDefaultUsers();
    final user =
        allUsers.isNotEmpty
            ? (allUsers.firstWhere(
              (u) => u.id == share.userId,
              orElse: () => allUsers.first,
            ))
            : null;

    return Container(
      margin: EdgeInsets.only(bottom: 16.h),

      child: [
        _buildShareHeader(user, share),
        SizedBox(height: 8.h),
        _buildShareContent(share),
        SizedBox(height: 8.h),
        _buildShareImages(share),
      ].toColumn(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  Widget _buildShareHeader(dynamic user, TopicShareEntity share) {
    return [
      Container(
        width: 44.w,
        height: 44.w,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          image: DecorationImage(
            image: AssetImage(user?.avatar ?? 'assets/resources/avatar1.png'),
            fit: BoxFit.cover,
          ),
          border: Border.all(color: Colors.black, width: 1),
        ),
      ),
      SizedBox(width: 8.w),
      [
        Text(
          user?.username ?? 'Unknown User',
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.w600,
            color: Colors.black,
            fontFamily: 'PoetsenOne',
          ),
        ),
        SizedBox(height: 2.h),
        Text(
          _formatTime(share.createdTime),
          style: TextStyle(fontSize: 12.sp, color: Colors.grey[600]),
        ),
      ].toColumn(crossAxisAlignment: CrossAxisAlignment.start).expanded(),
      Icon(AliIcons.iconInfo)
          .iconSize(20.sp)
          .iconColor(Colors.grey[600]!)
          .inkWell(onTap: () => _handleReport(share)),
    ].toRow(crossAxisAlignment: CrossAxisAlignment.center);
  }

  Widget _buildShareContent(TopicShareEntity share) {
    return Text(
      share.content,
      style: TextStyle(fontSize: 14.sp, color: Colors.black87, height: 1.4),
    );
  }

  Widget _buildShareImages(TopicShareEntity share) {
    if (share.imageUrls.isEmpty) {
      return SizedBox.shrink();
    }

    if (share.imageUrls.length == 1) {
      return Container(
        height: 120.h,
        width: double.infinity,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8.r),
          image: DecorationImage(
            image: AssetImage(share.imageUrls.first),
            fit: BoxFit.cover,
          ),
        ),
      );
    } else if (share.imageUrls.length == 2) {
      return [
        for (int i = 0; i < 2; i++)
          Expanded(
            child: Container(
              height: 120.h,
              margin: EdgeInsets.only(right: i == 0 ? 8.w : 0),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8.r),
                image: DecorationImage(
                  image: AssetImage(share.imageUrls[i]),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
      ].toRow();
    }

    return SizedBox.shrink();
  }

  Widget _buildBottomInputArea() {
    return Container(
      margin: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Color(0xFFF5F5DC),
        borderRadius: BorderRadius.circular(25.r),
        border: Border.all(color: Colors.black, width: 3),
      ),
      child: SafeArea(
        top: false,
        bottom: false,
        child: Container(
          height: 56.h,
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child:
              [
                Expanded(
                  child: TextField(
                    controller: _contentController,
                    decoration: InputDecoration(
                      hintText: 'say something...',
                      hintStyle: TextStyle(
                        color: Colors.grey[600],
                        fontSize: 16.sp,
                      ),
                      border: InputBorder.none,
                      isDense: true,
                    ),
                    style: TextStyle(fontSize: 16.sp, color: Colors.black),
                    maxLines: null,
                    textInputAction: TextInputAction.done,
                    onChanged: (value) {
                      setState(() {});
                    },
                  ),
                ),
                SizedBox(width: 12.w),
                Container(
                  width: 40.w,
                  height: 40.w,
                  decoration: BoxDecoration(
                    color: Color(0xFFFFD700),
                    shape: BoxShape.circle,
                  ),
                  child:
                      Icon(
                        AliIcons.iconPhoto,
                      ).iconSize(22.sp).iconColor(Colors.white).center(),
                ).inkWell(onTap: _selectImages),
                SizedBox(width: 8.w),
                Container(
                  width: 40.w,
                  height: 40.w,
                  decoration: BoxDecoration(
                    color: Color(0xFFFFD700),
                    shape: BoxShape.circle,
                  ),
                  child:
                      Icon(
                        AliIcons.iconSend,
                      ).iconSize(22.sp).iconColor(Colors.white).center(),
                ).inkWell(
                  onTap:
                      _contentController.text.trim().isNotEmpty
                          ? _sendShare
                          : null,
                ),
              ].toRow(),
        ),
      ),
    );
  }

  Future<void> _selectImages() async {
    final List<AssetEntity>? assets = await AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(
        maxAssets: 2,
        selectedAssets: _selectedAssets,
        requestType: RequestType.image,
        textDelegate: const AssetPickerTextDelegate(),
      ),
    );

    if (assets != null) {
      await _saveImagesToLocal(assets);

      setState(() {
        _selectedAssets = assets;
      });

      if (mounted) {
        ToastHelper.success(
          '${assets.length} image(s) selected',
          context: context,
        );
      }
    }
  }

  Future<List<String>> _saveImagesToLocal(List<AssetEntity> assets) async {
    final List<String> savedPaths = [];

    try {
      final Directory appDocDir = await getApplicationDocumentsDirectory();
      final String imagesDir = path.join(appDocDir.path, 'images');

      final Directory imagesDirObj = Directory(imagesDir);
      if (!await imagesDirObj.exists()) {
        await imagesDirObj.create(recursive: true);
      }

      for (int i = 0; i < assets.length; i++) {
        final AssetEntity asset = assets[i];
        final File? file = await asset.file;

        if (file != null) {
          final String fileName =
              '${DateTime.now().millisecondsSinceEpoch}_$i.jpg';
          final String savePath = path.join(imagesDir, fileName);

          final File savedFile = await file.copy(savePath);
          savedPaths.add(savedFile.path);
        }
      }
    } catch (e) {
      debugPrint('Error saving images: $e');
      if (mounted) {
        ToastHelper.error('Failed to save images', context: context);
      }
    }

    return savedPaths;
  }

  Future<void> _sendShare() async {
    final content = _contentController.text.trim();
    if (content.isEmpty) {
      ToastHelper.error('Please enter some content', context: context);
      return;
    }

    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) {
      PopupHelper.showLoginDialog(
        context,
        onLoginPressed: () {
          GoRouter.of(context).push('/login');
        },
        onCancelPressed: () {},
      );
      return;
    }

    try {
      List<String> imagePaths = [];
      if (_selectedAssets.isNotEmpty) {
        imagePaths = await _saveImagesToLocal(_selectedAssets);
      }

      TopicShareType shareType;
      if (imagePaths.isEmpty) {
        shareType = TopicShareType.textOnly;
      } else if (imagePaths.length == 1) {
        shareType = TopicShareType.textWithOneImage;
      } else {
        shareType = TopicShareType.textWithTwoImages;
      }

      final topicNotifier = ref.read(outingTopicProvider.notifier);
      final success = await topicNotifier.addShare(
        topicId: widget.topicId,
        userId: currentUser.id,
        content: content,
        shareType: shareType,
        imageUrls: imagePaths,
      );

      if (mounted) {
        if (success) {
          ToastHelper.success('Share sent successfully!', context: context);

          _contentController.clear();
          setState(() {
            _selectedAssets.clear();
          });

          Future.delayed(const Duration(milliseconds: 300), () {
            if (_scrollController.hasClients) {
              _scrollController.animateTo(
                _scrollController.position.maxScrollExtent,
                duration: const Duration(milliseconds: 500),
                curve: Curves.easeOut,
              );
            }
          });
        } else {
          ToastHelper.error('Failed to send share', context: context);
        }
      }
    } catch (e) {
      debugPrint('Error sending share: $e');
      if (mounted) {
        ToastHelper.error('Failed to send share', context: context);
      }
    }
  }

  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);

    if (difference.inMinutes < 1) {
      return 'Answered Just now';
    } else if (difference.inHours < 1) {
      return 'Answered ${difference.inMinutes}minutes ago';
    } else if (difference.inDays < 1) {
      return 'Answered ${difference.inHours}hours ago';
    } else if (difference.inDays < 7) {
      return 'Answered ${difference.inDays}days ago';
    } else {
      return 'Answered ${time.month}/${time.day}';
    }
  }

  void _handleReport(TopicShareEntity share) {
    PopupHelper.showReportDialog(
      context,
      onReportSubmitted: (ReportType reportType) async {
        final topicNotifier = ref.read(outingTopicProvider.notifier);
        final success = await topicNotifier.deleteShare(share.shareId);

        if (mounted) {
          if (success) {
            ToastHelper.success(
              'Content reported successfully',
              context: context,
            );
            setState(() {});
          } else {
            ToastHelper.error('Failed to remove content', context: context);
          }
        }
      },
      onCancelPressed: () {},
    );
  }
}
